# coding:utf-8

import socket
import _thread

# 目标软件<--TCP-->透传<--UDP-->外部主机
# 使用说明：
#   tcp_port修改为机械臂端口
#   udp_port修改为软件端口
tcp_port = 4000
udp_port = 4001
udp_gatewy_port = 4002
host = socket.gethostname()
print('host:', host, socket.gethostbyname(host))


class TCPState:
    def __init__(self):
        self.c, (self.host, self.port) = tcp_socket.accept()
        self.tcp_connection = True


tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_socket.bind((host, tcp_port))
tcp_socket.listen(5)
print('waiting for tcp connection...')
tcp_state = TCPState()
print('get tcp connection', tcp_state.host, tcp_state.port)

udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind((host, udp_gatewy_port))
print('waiting for udp host...')
data, addr = udp_socket.recvfrom(1024)
print('get udp connection', addr)


def UDP2TCP():
    while True:
        data, addr = udp_socket.recvfrom(1024)
        if tcp_state.tcp_connection is False:
            print('get udp, no tcp connection.')
            continue
        if data != b'':
            print(addr, 'get udp, send to tcp', data)
            tcp_state.c.send(data)

def TCP2UDP():
    while True:
        data = tcp_state.c.recv(1024)
        if data != b'':
            print('get tcp, send to udp', data)
            udp_socket.sendto(data, (host, udp_port))
        else:
            tcp_state.c.close()
            tcp_state.tcp_connection = False
            print('lost tcp connection, reconnecting..')
            tcp_state.c, (tcp_state.host, tcp_state.port) = tcp_socket.accept()
            tcp_state.tcp_connection = True
            print('Successful TCP reconnection.')


_thread.start_new_thread(UDP2TCP, ())
_thread.start_new_thread(TCP2UDP, ())


while True:
    pass
